<template>
  <div>
    <!-- 抽屉 -->
    <el-drawer
      :title="loginId==0?'添加用户':'修改用户'"
      size="40%"
      :visible.sync="drawer"
      direction="rtl"
      :before-close="closeDrawer">
      <div style="padding: 20px;">
        <el-form
          size="small"
          :model="formData"
          status-icon
          :rules="rules"
          ref="form"
          label-width="50px">
          <el-form-item v-if="loginId==0" label="账号" prop="loginId">
            <el-input v-model="formData.loginId"></el-input>
          </el-form-item>
          <el-form-item v-if="loginId==0" label="密码" prop="loginPwd">
            <el-input
              type="password"
              v-model="formData.loginPwd"
              autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="formData.sex">
              <el-radio label="男" value="男"></el-radio>
              <el-radio label="女" value="女"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="头像" prop="photo">
            <el-upload
              name="image"
              class="avatar-uploader"
              action="http://122.152.208.220:8081/admin/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="formData.photo" :src="formData.photo" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="formData.phone"></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="formData.type" placeholder="请选择类型">
              <el-option label="管理员" value="管理员"></el-option>
              <el-option label="校长" value="校长"></el-option>
              <el-option label="老师" value="老师"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="入职" prop="inDate">
            <el-date-picker
              v-model="formData.inDate"
              type="date"
              placeholder="请选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm()">{{loginId==0?'添加':'修改'}}</el-button>
            <el-button @click="resetForm()">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {$findByLoginId,$add,$upByLoginId} from '../api/adminAPI'
export default {
  data(){
    // 验证账号
    var checkLoginId = async (rule, value, callback) => {
      if (!value) {
        callback(new Error("账号不能为空"));
      }else{
        let ret = await $findByLoginId({loginId:value})
        if(ret){
          callback(new Error("账号不能重复"));
        }else{
          callback();
        }
      }
    };
    // 验证密码
    var checkLoginPwd = (rule, value, callback) => {
      if (!value) {
        callback(new Error("密码不能为空"));
      } else {
        callback();
      }
    };
    // 验证电话
    var checkPhone = (rule, value, callback)=>{
      if (!value) {
        callback(new Error("电话不能为空"));
      }else{
        let reg = /^1\d{10}$/
        if(!reg.test(value)){
          callback(new Error("手机号码格式错误"));
        }else{
          callback();
        }
      }
    }
    return {
      //当前编辑的用户id
      loginId:0,
      //是否打开抽屉
      drawer: false,
      //表单数据
      formData: {
        loginId: '',
        loginPwd: '',
        name:'',
        sex:'男',
        photo:'',
        phone:'',
        type:'',
        inDate:''
      },
      //表单验证
      rules: {
        loginId: [{ validator: checkLoginId, trigger: "blur" }],
        loginPwd: [{ validator: checkLoginPwd, trigger: "blur" }],
        phone:[{ validator: checkPhone, trigger: "blur" }],
      },
    }
  },
  methods:{
    //关闭抽屉的方法
    closeDrawer(done){
      this.$refs.form.resetFields();
      this.loginId = 0
      done()
    },
    //表单提交方法
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if(this.loginId==0){
            let ret = await $add(this.formData)
            if(ret.code==0){
              this.$message({
                message:'添加成功',
                type:'success'
              })
              this.$emit('sync-list')
            }else{
              this.$message({
                message:'添加失败',
                type:'error'
              })
            }
          }else{
            let ret = await $upByLoginId(this.formData)
            if(ret.code==0){
              this.$message({
                message:'修改成功',
                type:'success'
              })
              this.$emit('sync-list')
            }else{
              this.$message({
                message:'修改失败',
                type:'error'
              })
            }
          }
          
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //表单重置方法
    resetForm() {
      this.$refs.form.resetFields();
    },
    // 上传成功
    handleAvatarSuccess(res, file) {
      this.formData.photo = res.data
    },
    // 上传之前
    beforeAvatarUpload(file) {
      let types = ['image/jpeg','image/png','image/gif']
      const isTp = types.includes(file.type);
      const is1M = file.size / 1024 / 1024 < 1;

      if (!isTp) {
        this.$message.error('只能上传 jpg png gif 格式的图片!');
      }
      if (!is1M) {
        this.$message.error('上传头像大小不能超过 1MB!');
      }
      return isTp && is1M;
    }
  },
  watch:{
    loginId(nval){
      if(nval!=0){
        $findByLoginId({loginId:nval}).then(ret=>{
          this.formData = ret
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader {
  width: 158px;
  height: 158px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 158px;
  height: 158px;
  line-height: 158px;
  text-align: center;
}
.avatar-uploader-icon:hover{
  color: #409EFF;
}
.avatar {
  width: 158px;
  height: 158px;
  display: block;
}
</style>